// pages/search/search.js
import api from '../../../config/api'
import path from '../../../config/path'
const { $Toast } = require('../../../dist/base/index');
const bubbleMixin = require('../../../utils/page-mixin');
const app = getApp()

Page({
  ...bubbleMixin,
  data: {
    picLocal: app.globalData.picLocal,
    showRight: false,
    condition: '',
    roomType: null,
    roomTypeStr: '全部户型',
    bottomLoading: false,
    minRentMoney: '',
    maxRentMoney: '',
    chooseTags: [],
    region: ['四川省', '成都市', '全部'],
    houseList: [],
    // 户型选项
    roomTypeOptions: [
      { value: null, label: '全部户型' },
      { value: '一室一厅', label: '一室一厅' },
      { value: '两室一厅', label: '两室一厅' },
      { value: '单间', label: '单间' }
    ],
    pageData: {
      pageNo: 1,
      pageSize: 10,
      count: 0,
    }
  },

  onLoad: function (options) {
    this.setData({
      condition: options.condition || ''
    })
    this.fetchList({ append: false })
  },

  onReachBottom: function () {
    this.fetchList({ append: true })
  },

  // 切换筛选面板
  toggleRight() {
    this.setData({
      showRight: !this.data.showRight
    })
  },

  // 设置户型
  setRoomType(e) {
    const type = e.currentTarget.dataset.type
    const option = this.data.roomTypeOptions.find(opt => opt.value === type)
    
    this.setData({
      roomType: type,
      roomTypeStr: option ? option.label : '全部户型'
    })
  },

  // 区域选择
  bindRegionChange(e) {
    this.setData({
      region: e.detail.value
    })
  },

  // 清空筛选条件
  clearInfo() {
    this.setData({
      roomType: null,
      roomTypeStr: '全部户型',
      minRentMoney: '',
      maxRentMoney: '',
      region: ['四川省', '成都市', '全部'],
      chooseTags: []
    })
  },

  // 搜索
  searchHouse() {
    this.setData({
      showRight: false,
      houseList: [],
      pageData: {
        pageNo: 1,
        pageSize: this.data.pageData.pageSize,
        count: 0
      }
    })
    this.fetchList({ append: false })
  },

  // 输入框变化
  minRentMoneyInput(e) {
    this.setData({ minRentMoney: e.detail.value })
  },

  maxRentMoneyInput(e) {
    this.setData({ maxRentMoney: e.detail.value })
  },

  conditionInput(e) {
    this.setData({ condition: e.detail.value })
  },

  // 清空搜索框
  clearSearch() {
    this.setData({ condition: '' })
  },

  // 搜索按钮点击
  onSearch() {
    this.searchHouse()
  },

  // 构建查询参数 - 根据后端接口调整
  buildQuery(pageNo) {
    const city = this.data.region[1] // 使用城市参数
    const query = {
      pageNo: pageNo,
      pageSize: this.data.pageData.pageSize,
      keyword: this.data.condition || ''
    }

    // 添加城市筛选
    if (city && city !== '全部') {
      query.city = city
    }

    // 添加价格筛选
    if (this.data.minRentMoney) {
      query.minPrice = parseFloat(this.data.minRentMoney)
    }
    if (this.data.maxRentMoney) {
      query.maxPrice = parseFloat(this.data.maxRentMoney)
    }

    // 添加户型筛选
    if (this.data.roomType) {
      query.roomType = this.data.roomType
    }

    console.log('构建的查询参数:', query)
    return query
  },

  // 获取房源列表
  fetchList({ append }) {
    if (append && this.data.houseList.length >= this.data.pageData.count && this.data.pageData.count !== 0) {
      $Toast({ content: '没有更多数据了' })
      return
    }

    this.setData({ bottomLoading: true })
    const nextPage = append ? this.data.pageData.pageNo + 1 : 1
    const params = this.buildQuery(nextPage)
    
    console.log('请求参数:', params)
    
    api.get('house', path.path.getHouseList, params).then(res => {
      console.log('搜索返回结果:', res)
      
      if (res.code === 200) {
        // 根据后端返回的数据结构调整
        const pageData = res.data
        const list = pageData.content || pageData.records || pageData.list || []
        const total = pageData.totalElements || pageData.total || 0
        
        console.log('房源列表数据:', list)
        
        this.setData({
          houseList: append ? this.data.houseList.concat(list) : list,
          'pageData.pageNo': nextPage,
          'pageData.count': total
        })

        if (total === 0 && !append) {
          $Toast({ content: '暂无符合条件的房源' })
        }
      } else {
        $Toast({ content: res.message || '搜索失败' })
      }
    }).catch(err => {
      console.log('搜索错误:', err)
      $Toast({ content: '加载失败，请重试' })
    }).finally(() => {
      this.setData({ bottomLoading: false })
    })
  },

  // 跳转到房源详情
  toHouseInfo(e) {
    const houseId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../houseInfo/houseInfo?id=' + houseId,
    })
  }
})